package com.iplant.wms.serviceImpl.dao.pkg;

import com.iplant.wms.service.basicenum.mss.MSSPackageType;
import com.iplant.base.po.OutResult;
import com.iplant.base.po.Pagination;
import com.iplant.base.po.enums.ExceptionTypes;
import com.iplant.base.utils.general.StringUtils;
import com.iplant.base.utils.sql.BaseDAO;
import com.iplant.basic.service.po.bms.BMSEmployee;
import com.iplant.wms.service.po.pkg.MSSPackageProp;
import com.iplant.wms.service.po.pkg.MSSPackageRule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

public class MSSPackagePropDAO extends BaseDAO {

    private static MSSPackagePropDAO Instance = null;
    private static Logger logger = LoggerFactory.getLogger(MSSPackagePropDAO.class);

    private static int PropTotalMax = 5;

    private MSSPackagePropDAO() {
        super();

        setTableName("mss_packageprop");
    }

    public static MSSPackagePropDAO getInstance() {
        if (Instance == null) {
            Instance = new MSSPackagePropDAO();
        }
        return Instance;
    }


    protected void MSS_CreatePackageProp(BMSEmployee wLoginUser, int wRuleID, OutResult<Integer> wErrorCode) {

        List<Map<String, Object>> wParwmsList = new ArrayList<>();
        Map<String, Object> wParwms;

        for (MSSPackageType wMSSPackageType : MSSPackageType.values()) {
            if (wMSSPackageType == null || wMSSPackageType.getValue() <= 0) {
                continue;
            }
            wParwms = new HashMap<>();

            wParwms.put("Name", wMSSPackageType.getLabel());
            wParwms.put("Code", wMSSPackageType.name());
            wParwms.put("RuleID", wRuleID);
            wParwms.put("TypeID", wMSSPackageType.getValue());
            wParwms.put("MaterialNumber", 1.0);
            wParwms.put("UnitID", 0);

            wParwms.put("EditorID", wLoginUser.getID());
            wParwms.put("EditTime", Calendar.getInstance());
            wParwms.put("CreatorID", wLoginUser.getID());
            wParwms.put("CreateTime", Calendar.getInstance());
            wParwms.put("Active", 1);

            wParwmsList.add(wParwms);

        }

        this.Insert(wParwmsList);

    }

    public List<MSSPackageProp> MSS_QueryPackagePropList(BMSEmployee wLoginUser, int wRuleID, String wRuleCode,
                                                         OutResult<Integer> wErrorCode) {

        List<MSSPackageProp> wMSSPackagePropList = null;
        try {
            if (wRuleID > 0) {
                wMSSPackagePropList =
                        this.MSS_QueryPackagePropList(wLoginUser, wRuleID, "", "", "", null, Pagination.getMaxSize(),
                                                      wErrorCode);
            } else if (StringUtils.isNotEmpty(wRuleCode)) {
                wMSSPackagePropList =
                        this.MSS_QueryPackagePropList(wLoginUser, -1, wRuleCode, "", "", null, Pagination.getMaxSize(),
                                                      wErrorCode);
            } else {
                wErrorCode.Result = ExceptionTypes.Parameter.getValue();
                return new ArrayList<>();
            }


            if (wErrorCode.Result != 0) {
                return wMSSPackagePropList;
            }

            if (wMSSPackagePropList != null && wMSSPackagePropList.size() != PropTotalMax) {

                if (wRuleID <= 0) {
                    MSSPackageRule mssPackageRule =
                            MSSPackageRuleDAO.getInstance().MSS_QueryPackageRule(wLoginUser, -1, wRuleCode, wErrorCode);
                    if (wErrorCode.Result != 0) {
                        return wMSSPackagePropList;
                    }
                    if (mssPackageRule == null || mssPackageRule.ID <= 0) {
                        return wMSSPackagePropList;
                    }
                    wRuleID = mssPackageRule.ID;
                }

                Map<String, Object> wDeleteParwms = new HashMap<>();
                wDeleteParwms.put("RuleID", wRuleID);
                this.Delete(wDeleteParwms, " and ID>0 ");

                this.MSS_CreatePackageProp(wLoginUser, wRuleID, wErrorCode);
                if (wErrorCode.Result != 0) {
                    return wMSSPackagePropList;
                }


                wMSSPackagePropList =
                        this.MSS_QueryPackagePropList(wLoginUser, wRuleID, "", "", "", null, Pagination.getMaxSize(),
                                                      wErrorCode);
            }


        } catch (Exception ex) {

            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            logger.error("MSS_QueryPackagePropList", ex);
        }
        return wMSSPackagePropList;
    }

    public void MSS_UpdatePackageProp(BMSEmployee wLoginUser, MSSPackageProp wPackageProp,
                                      OutResult<Integer> wErrorCode) {
        wErrorCode.set(0);

        try {
            if (wPackageProp == null || wPackageProp.RuleID <= 0 || StringUtils.isEmpty(wPackageProp.Code)) {
                wErrorCode.set(ExceptionTypes.Parameter.getValue());
                return;
            }
            MSSPackageProp wPackagePropO = this.MSS_CheckPackageProp(wLoginUser, wPackageProp, wErrorCode);
            if (wPackagePropO.ID > 0) {
                wErrorCode.set(ExceptionTypes.Duplication.getValue());
            }
            if (wErrorCode.Result != 0) {
                return;
            }

            Map<String, Object> wParwms = new HashMap<String, Object>();

            wParwms.put("MaterialNumber", wPackageProp.MaterialNumber);
          //  wParwms.put("UnitID", wPackageProp.UnitID);
            wParwms.put("Essence", wPackageProp.Essence);
            wParwms.put("Packing", wPackageProp.Packing);
            wParwms.put("InStockLabel", wPackageProp.InStockLabel);
            wParwms.put("ReplenishmentLabel", wPackageProp.ReplenishmentLabel);
            wParwms.put("OutStockLabel", wPackageProp.OutStockLabel);
            wParwms.put("SerialNumber", wPackageProp.SerialNumber);
            wParwms.put("ContentLength", wPackageProp.ContentLength);
            wParwms.put("ContentWidth", wPackageProp.ContentWidth);
            wParwms.put("ContentHeight", wPackageProp.ContentHeight);
            wParwms.put("Weight", wPackageProp.Weight);
            wParwms.put("Volume", wPackageProp.Volume);
            wParwms.put("HiNumber", wPackageProp.HiNumber);
            wParwms.put("TiNumber", wPackageProp.TiNumber);
            wParwms.put("Length", wPackageProp.Length);
            wParwms.put("Width", wPackageProp.Width);
            wParwms.put("Height", wPackageProp.Height);

            wParwms.put("EditorID", wLoginUser.getID());
            wParwms.put("EditTime", Calendar.getInstance());
            wParwms.put("Description", wPackageProp.Description);

            if (wPackageProp.ID > 0) {
                wParwms.put("ID", wPackageProp.ID);
                super.Update(super.getTableName("mss_packageprop"), "ID", wParwms);
            } else {
                wErrorCode.set(ExceptionTypes.Parameter.getValue());
                return;
//
//                wParwms.put("CreatorID", wLoginUser.getID());
//                wParwms.put("CreateTime", Calendar.getInstance());
//                wPackageProp.ID = super.Insert(super.getTableName("mss_packageprop"), wParwms);
            }

        } catch (Exception ex) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            logger.error("MSS_UpdatePackageProp", ex);
        }
    }


    public void MSS_DeletePackageProp(BMSEmployee wLoginUser, int wRuleID, OutResult<Integer> wErrorCode) {
        wErrorCode.set(0);

        try {
            if (wRuleID <= 0) {
                wErrorCode.set(ExceptionTypes.Parameter.getValue());
                return;
            }
            Map<String, Object> wDeleteParwms = new HashMap<>();
            wDeleteParwms.put("RuleID", wRuleID);
            this.Delete(wDeleteParwms, " and ID>0 ");

        } catch (Exception ex) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            logger.error("MSS_DeletePackageProp", ex);
        }
    }


    public void MSS_ActivePackageProp(BMSEmployee wLoginUser, MSSPackageProp wPackageProp, int wActive,
                                      OutResult<Integer> wErrorCode) {
        wErrorCode.set(0);
        // 判断客户信息是否存在(中国：统一社会信用代码，国外:提醒是否有重复）

        try {
            if (wPackageProp == null || wPackageProp.ID <= 0) {
                wErrorCode.set(ExceptionTypes.Parameter.getValue());
                return;
            }

            Map<String, Object> wParwms = new HashMap<String, Object>();

            wParwms.put("ID", wPackageProp.ID);
            wParwms.put("EditorID", wLoginUser.getID());
            wParwms.put("EditTime", Calendar.getInstance());
            wParwms.put("Active", wActive);
            super.Update(super.getTableName("mss_packageprop"), "ID", wParwms);

        } catch (Exception ex) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());

            logger.error("MSS_ActivePackageProp", ex);
        }
    }

    public List<MSSPackageProp> MSS_QueryPackagePropList(
            BMSEmployee wLoginUser, int wRuleID, String wRuleCode, String wName, String wCode,
            List<Integer> wActive, Pagination wPagination, OutResult<Integer> wErrorCode) {
        List<MSSPackageProp> wMSSPackagePropList = new ArrayList<MSSPackageProp>();
        wErrorCode.set(0);

        try {


            if (wActive == null) {
                wActive = new ArrayList<>();
            }

            wActive.removeIf(p -> p <= 0);
            // Step02:查询
            Map<String, Object> wParwms = new HashMap<String, Object>();
            String wSQLText = "";
            wSQLText = StringUtils.Format(
                    "Select t.*,t1.Name as RuleName,t1.Code as RuleCode,"
                            + " t3.Name as CreatorName ,t4.Name as EditorName  from {0}.mss_packageprop t  "
                            + " left join {0}.mss_packagerule t1 on  t.RuleID=t1.ID "
                            + " left join {0}.mbs_user t3 on t.CreatorID=t3.ID "
                            + " left join {0}.mbs_user t4 on t.EditorID=t4.ID "
                            + " where   (:Code =''''  or  t.Code=:Code)   AND (:RuleID<=0 or  t.RuleID=:RuleID)"
                            + " and  (:RuleCode =''''  or  t1.Code=:RuleCode) "
                            + " AND (:Active = '''' or  t.Active in ({1}) ) AND (:Name = '''' or  t.Name like :Name) ",
                    super.getDBName(), wActive.size() > 0 ?
                            StringUtils.Join(",", wActive) : "0");

            wSQLText = this.DMLChange(wSQLText);

            wParwms.put("Code", wCode);
            wParwms.put("RuleID", wRuleID);
            wParwms.put("RuleCode", wRuleCode);
            wParwms.put("Active", StringUtils.Join(",", wActive));
            wParwms.put("Name", StringUtils.isEmpty(wName) ? "" : ("%" + wName + "%"));

            wMSSPackagePropList = super.QueryForList(wSQLText, wParwms, wPagination, MSSPackageProp.class);

            // Step03:配置系统
        } catch (Exception ex) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            logger.error("MSS_QueryPackagePropList", ex);
        }
        return wMSSPackagePropList;
    }


    public MSSPackageProp MSS_QueryPackageProp(BMSEmployee wLoginUser, int wRuleID, String wRuleCode, String wCode,
                                               OutResult<Integer> wErrorCode) {
        MSSPackageProp wResult = new MSSPackageProp();

        try {
            if (StringUtils.isEmpty(wCode) || (wRuleID <= 0 && StringUtils.isEmpty(wCode))) {
                wErrorCode.Result = ExceptionTypes.Parameter.getValue();
                return wResult;
            }

            List<MSSPackageProp> wMSSPackagePropList  = this.MSS_QueryPackagePropList(
                    wLoginUser, wRuleID, wRuleCode, "", wCode, null, Pagination.getDefault(), wErrorCode);


            if (wErrorCode.Result != 0) {
                return wResult;
            }

            if (wMSSPackagePropList != null && wMSSPackagePropList.size() > 0) {
                wResult = wMSSPackagePropList.get(0);
            }


        } catch (Exception ex) {

            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            logger.error("MSS_QueryPackageProp", ex);
        }
        return wResult;

    }


    public MSSPackageProp MSS_CheckPackageProp(BMSEmployee wLoginUser, MSSPackageProp wMSSPackageProp,
                                               OutResult<Integer> wErrorCode) {
        MSSPackageProp wPackageProp = new MSSPackageProp();
        wErrorCode.set(0);

        try {

            // Step0:查询
            Map<String, Object> wParwms = new HashMap<String, Object>();
            String wSQLText = StringUtils.Format(
                    "Select * from {0}.mss_packageprop "
                            + " where ID!=:ID and ( RuleID=:RuleID and  ( Name =:Name or  Code=:Code)) ",
                    super.getDBName());
            wParwms.clear();
            wParwms.put("ID", wMSSPackageProp.ID);
            wParwms.put("Name", wMSSPackageProp.Name);
            wParwms.put("Code", wMSSPackageProp.Code);
            wParwms.put("RuleID", wMSSPackageProp.RuleID);

            wSQLText = this.DMLChange(wSQLText);
            List<Map<String, Object>> wQueryResultList = super.queryForList(wSQLText, wParwms);
            for (Map<String, Object> wSqlDataReader : wQueryResultList) {
                wPackageProp.ID = StringUtils.parseInt(wSqlDataReader.get("ID"));
                wPackageProp.Name = StringUtils.parseString(wSqlDataReader.get("Name"));
                wPackageProp.Code = StringUtils.parseString(wSqlDataReader.get("Code"));

                wPackageProp.CreatorID = StringUtils.parseInt(wSqlDataReader.get("CreatorID"));
                wPackageProp.CreateTime = StringUtils.parseCalendar(wSqlDataReader.get("CreateTime"));
                wPackageProp.EditorID = StringUtils.parseInt(wSqlDataReader.get("EditorID"));
                wPackageProp.EditTime = StringUtils.parseCalendar(wSqlDataReader.get("EditTime"));
                wPackageProp.Active = StringUtils.parseInt(wSqlDataReader.get("Active"));

            }

        } catch (Exception ex) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            logger.error("MSS_CheckPackageProp", ex);
        }
        return wPackageProp;
    }

}
